package edu.lingnan.house.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.lingnan.house.mapper.TbUserMapper;
import edu.lingnan.house.mapper.UserMapper;
import edu.lingnan.house.pojo.TbUser;
import edu.lingnan.house.service.UserService;
import edu.lingnan.house.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

public class UserServiceImpl extends ServiceImpl<UserMapper, TbUser> implements UserService {

    @Autowired
    private TbUserMapper tbUserMapper;

    //  检查密码
    @Override
    public Result<Void> checkPassword(String password, String comfirmPwd) {
        if ("".equals(password)||password==null){
            return new Result<>(201,"密码不能为空");
        }
        if ("".equals(comfirmPwd)||comfirmPwd==null){
            return new Result<>(202,"确认密码不能为空");
        }
        if (!password.equals(comfirmPwd)){
            return new Result<>(203,"两次密码不一致");
        }else {
            return new  Result<>(200,"密码相同");
        }
    }

    //封装一个方法，用于加密
    private String md5Password(String password,String salt){
        String md5Pwd=password+salt;
        //调用API加密
        for (int i=0;i<3;i++){
            md5Pwd = DigestUtils.md5DigestAsHex(md5Pwd.getBytes());
        }
        return md5Pwd;
    }

    @Override
    public Result<Void> updateUInfo(String id, String name, String headPortrait, String password, String UPpassword, String TUPpassword) {
        if (password==null||"".equals(password))return new Result<>(201,"密码不能为空");
        QueryWrapper<TbUser> wrapper=new QueryWrapper<>();
        wrapper.eq("id",id);
        TbUser tbUser = tbUserMapper.selectOne(wrapper);
        if (tbUser == null)return new Result<>(502,"数据可能被删");
        String salt=tbUser.getSalt();
        String regMD5Pwd=tbUser.getPassword();
        String md5Password = md5Password(password,salt);
        if (!md5Password.equals(regMD5Pwd))return new Result<>(503,"密码错误");

        Result result2=checkPassword(UPpassword,TUPpassword);
//        String newmd5Password= md5Password(UPpassword,salt);
        if (result2.getCode()!=200)return result2;
//        tbUser.setCreateUser(name).setModifyTime(LocalDateTime.now()).setPassword(newmd5Password);
        int row = tbUserMapper.updateById(tbUser);
        if (row!=1){
            return  new Result<>(503,"更新失败");
        }else {
            return new Result<>(200,"更新成功");
        }
    }
}
